package com.bittech.client.service;

import com.bittech.util.CommUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Properties;

/**
 * @Author: yuisama
 * @Date: 2019-06-13 11:19
 * @Description:客户端使用Socket连接服务器，返回客户端套接字便于后续与服务器交互
 */

public class Connect2Server {
    private Socket client;
    private InputStream clientRead;
    private OutputStream clientWrite;

   public Connect2Server(){
        Properties properties = CommUtil.loadProperties("socket.properties");
        String server_address = properties.getProperty("server_address");
        int port = Integer.valueOf(properties.getProperty("port"));
        try {
            client = new Socket(server_address,port);
            clientRead =  client.getInputStream();
            clientWrite = client.getOutputStream();
        } catch (IOException e) {
            System.err.println("连接服务器失败");
            e.printStackTrace();
        }
    }

    public InputStream getClientRead() {
        return clientRead;
    }

    public OutputStream getClientWrite() {
        return clientWrite;
    }

    public Socket getClient() {
        return client;
    }

    /**
     * 关闭客户端所有连接
     */
    public void closeClient() {
        try {
            clientRead.close();
            clientWrite.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
